package top.fkxuexi.blogapi.core.config;


import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * 至于白名单和黑名单，这个后面再说
 */

@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidConfig {

    @Setter@Getter private Integer initialSize;
    @Setter@Getter private Integer maxActive;
    @Setter@Getter private String filters;
    @Setter@Getter private String url;
    @Setter@Getter private String username;
    @Setter@Getter private String password;
    @Setter@Getter private String loginUsername;
    @Setter@Getter private String loginPassword;


    @Bean
    public ServletRegistrationBean druidServlet(){

        ServletRegistrationBean servletRegistrationBean
                = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
     /*   // IP白名单
        servletRegistrationBean.addInitParameter("allow", "192.168.2.25,127.0.0.1");
        // IP黑名单(共同存在时，deny优先于allow)
        servletRegistrationBean.addInitParameter("deny", "192.168.1.100");*/
        //控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", loginUsername);
        servletRegistrationBean.addInitParameter("loginPassword", loginPassword);
        //是否能够重置数据 禁用HTML页面上的“Reset All”功能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }


    @Bean(destroyMethod = "close",initMethod = "init")     //声明其为Bean实例 括号里面的是防止：(*) property for user to setup出现
    public DataSource dataSource() throws SQLException {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setInitialSize(initialSize);
        datasource.setMaxActive(maxActive);
        datasource.setFilters(filters);
        datasource.setUrl(url);
        datasource.setPassword(password);
        datasource.setUsername(username);
        return datasource;
    }

}
